#!/bin/bash
############################################################################
# Copyright (C) 2007 Lawrence Livermore National Security, LLC
# Produced at Lawrence Livermore National Laboratory.
# Written by Jim Garlick <garlick@llnl.gov>.
# UCRL-CODE-235119
# 
# This file is part of nfsroot, a network root file system utility.
# 
# nfsroot is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# nfsroot is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along
# with nfsroot; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
############################################################################
#
# rc.nfsroot-unionfs - nfsroot startup (unionfs method)
#
# Root is a union of /readonly (shared ro nfs root) and /writeable (ramdisk).
#
export PATH=/bin:/sbin:/usr/bin:/usr/sbin
PREINITPROG=/etc/rc.nfsroot-init
configfile=/etc/sysconfig/nfsroot
if [ -f $configfile ]; then
   . $configfile
fi
prog=rc.nfsroot-unionfs

if touch / 2>/dev/null; then
   echo "${prog}: root file system is read-write" >&2
   return 1
fi

modprobe unionfs 2>/dev/null
result=$?

if [ ${result} != 0 ]; then
   echo "${prog}: unionfs is unavailable"
   return 1
fi

mnt_options="mode=755,nr_inodes=0${TMPFSMAX:+,size=${TMPFSMAX}}"
echo "${prog}: mounting ramdisk with ${mnt_options}"
if ! mount -n -t tmpfs -o${mnt_options} none /writeable; then
   echo "${prog}: mount failed"
   return 1
fi

if ! mount -n -t unionfs -o dirs=/writeable=rw:/=ro none /mnt; then
   echo "${prog}: mount failed"
   umount /writeable
   return 1
fi 
mount -n --move /writeable /mnt/writeable

cd /mnt
mkdir -p readonly
pivot_root . readonly
echo "${prog}: passing control to ${PREINITPROG}" >&2
exec chroot . ${PREINITPROG} "$@" <dev/console >dev/console 2>&1
return 1
